<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="isHide ? 1 : 6" :xs="24" class="relative">
        <div class="app-container-tree-border">
          <project-tree-select-inner class="cd-mb8" :projectId="projectId" @changeProject="changeProject" />
          <el-input class="cd-mb8" v-model="filterText" placeholder="请输入" clearable size="small"
            prefix-icon="el-icon-search" />
          <el-tree class="input-tree" :data="treeList" :props="defaultProps" :filter-node-method="filterNode" ref="tree"
            node-key="id" highlight-current @node-click="handleNodeClick">
            <div slot-scope="{ node, data }" class="custom-tree-node" :title="node.label" v-text="node.label"></div>
          </el-tree>
          <div class="tree-hide-button iconfont" :class="isHide ? 'icon-xiangyou' : 'icon-xiangzuo'"
            @click="() => { isHide = !isHide }">
          </div>
        </div>
      </el-col>
      <el-col :span="isHide ? 23 : 18" :xs="24">
        <div class="app-container-table-border">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <!-- <el-form-item label="标段id" prop="bdId">
              <el-input v-model="queryParams.bdId" placeholder="请输入标段id" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="供应商id" prop="gysId">
              <el-input v-model="queryParams.gysId" placeholder="请输入供应商id" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="所属时间" prop="belongDate">
              <el-date-picker clearable v-model="queryParams.belongDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择所属时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="编制日期" prop="weaveDate">
              <el-date-picker clearable v-model="queryParams.weaveDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择编制日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="开始时间" prop="beginDate">
              <el-date-picker clearable v-model="queryParams.beginDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker clearable v-model="queryParams.endDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="当前环节" prop="unit">
              <el-input v-model="queryParams.unit" placeholder="请输入当前环节" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="工作流状态" prop="workflowsStateus">
              <el-input v-model="queryParams.workflowsStateus" placeholder="请输入工作流状态" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="发送状态" prop="sendStateus">
              <el-input v-model="queryParams.sendStateus" placeholder="请输入发送状态" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="签收状态" prop="signStateus">
              <el-input v-model="queryParams.signStateus" placeholder="请输入签收状态" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>-->
            <el-row v-if="treeInfo && treeInfo.type == 'supplier'" :gutter="10"
              class="mb8 cd-pr8 top-right-btn small-line-height">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                  v-hasPermi="['ma:materialPlan:add']">新增</el-button>
              </el-col>
              <!-- <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                  v-hasPermi="['ma:materialPlan:export']">导出</el-button>
              </el-col> -->
              <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
            </el-row>
          </el-form>
          <el-table border stripe v-loading="loading" :data="materialPlanList"
            @selection-change="handleSelectionChange">
            <el-table-column type="index" label="序号" width="55" align="center" />
            <el-table-column label="所属期间" align="center" prop="belongDate" min-width="120">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.belongDate, '{y}年{m}月') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="编制日期" align="center" prop="weaveDate" min-width="120">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.weaveDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="开始时间" align="center" prop="beginDate" min-width="120">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.beginDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="结束时间" align="center" prop="endDate" min-width="120">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="审批状态" align="center" prop="workflowsStateus" min-width="100">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.report_status" :value="scope.row.workflowsStateus" />
              </template>
            </el-table-column>
            <el-table-column label="当前节点" align="center" prop="currName" min-width="100">
              <template slot-scope="scope">
                <el-link type="primary" @click="showApproveLog(scope.row)">{{ scope.row.currName }}</el-link>
              </template>
            </el-table-column>
            <el-table-column label="签收状态" align="center" prop="signStateus" min-width="100">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sign_status" :value="scope.row.signStateus" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-view" @click="onViewDeatils(scope.row)"
                  v-hasPermi="['ma:materialPlan:view']">查看报表</el-button>
                <el-button v-if="canOperation(scope.row)" size="mini" type="text" icon="el-icon-edit"
                  @click="onUpdateDeatils(scope.row)" v-hasPermi="['ma:materialPlan:editDetails']">编辑明细</el-button>
                <!-- <el-button v-if="canOperation(scope.row)" size="mini" type="text" icon="el-icon-edit"
                  @click="handleUpdate(scope.row)" v-hasPermi="['ma:materialPlan:edit']">修改</el-button>
                <el-button v-if="canOperation(scope.row)" size="mini" type="text" icon="el-icon-delete"
                  @click="handleDelete(scope.row)" v-hasPermi="['ma:materialPlan:remove']">删除</el-button>
                <el-button v-if="canOperation(scope.row)" size="mini" type="text" icon="el-icon-document"
                  @click="onExamine(scope.row)" v-hasPermi="['ma:materialPlan:approve']">发起审批</el-button> -->
                <el-button v-if="scope.row.workflowsStateus == '22' && scope.row.signStateus != '1'" size="mini"
                  type="text" icon="el-icon-circle-check" @click="onSign(scope.row)"
                  v-hasPermi="['ma:materialPlan:sign']">确认</el-button>
                <el-dropdown v-if="canOperation(scope.row)" size="mini"
                  @command="(command) => handleCommand(command, scope.row)"
                  v-hasPermi="['ma:materialPlan:edit', 'ma:materialPlan:remove', 'ma:materialPlan:approve']">
                  <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="handleUpdate" icon="el-icon-edit"
                      v-hasPermi="['ma:materialPlan:edit']">修改</el-dropdown-item>
                    <el-dropdown-item command="handleDelete" icon="el-icon-delete"
                      v-hasPermi="['ma:materialPlan:remove']">删除</el-dropdown-item>
                    <el-dropdown-item command="onExamine" icon="el-icon-document"
                      v-hasPermi="['ma:materialPlan:approve']">发起审批</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
      </el-col>
    </el-row>
    <!-- 添加或修改材料计划对话框 -->
    <jy-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属期间" prop="belongDate">
              <el-date-picker clearable v-model="form.belongDate" type="month" value-format="yyyy-MM-dd"
                placeholder="请选择所属期间" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="编制日期" prop="weaveDate">
              <el-date-picker clearable v-model="form.weaveDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择编制日期" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开始时间" prop="beginDate">
              <el-date-picker clearable v-model="form.beginDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择开始时间" style="width: 100%;" :picker-options="beginPickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker clearable v-model="form.endDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择结束时间" style="width: 100%;" :picker-options="endPickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </jy-dialog>
    <plan-details ref="planDetailsRef" @callBack="handleQuery" />
    <plan-details-view-drawer ref="planDetailsViewRef" />
    <examine-and-approve ref="examineAndApproveRef" @callBack="handleQuery" />
    <approve-log ref="approveLogRef" />
  </div>
</template>

<script>
import { listMaterialPlan, getMaterialPlan, delMaterialPlan, addMaterialPlan, updateMaterialPlan } from "@/api/ma/materialPlan";
import { querySupplierTreeList } from "@/api/base/bsBd";
import { mapGetters } from "vuex";
import { getDateDiff, getMonthStartAndEnd } from '@/utils';
import planDetails from './planDetails.vue';
import ExamineAndApprove from './examine-and-approve.vue';
import planDetailsViewDrawer from './planDetailsViewDrawer.vue';
import ApproveLog from './approve-log.vue';

export default {
  name: "MaterialPlan",
  dicts: ['report_status', 'sign_status'],
  components: { planDetails, ExamineAndApprove, planDetailsViewDrawer, ApproveLog },
  data () {
    return {
      isHide: false,
      treeList: [],
      treeInfo: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      filterText: undefined,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 材料计划表格数据
      materialPlanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bdId: undefined,
        zdId: undefined,
        gysId: undefined,
        type: undefined,
        belongDate: undefined,
        weaveDate: undefined,
        beginDate: undefined,
        endDate: undefined,
        unit: undefined,
        workflowsStateus: undefined,
        sendStateus: undefined,
        signStateus: undefined,
      },
      projectId: undefined,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // planId: [
        //   { required: true, message: "计划id不能为空", trigger: "blur" }
        // ],
        // bdId: [
        //   { required: true, message: "标段id不能为空", trigger: "blur" }
        // ],
        gysId: [
          { required: true, message: "供应商id不能为空", trigger: "blur" }
        ],
        // type: [
        //   { required: true, message: "类型id不能为空", trigger: "change" }
        // ],
        belongDate: [
          { required: true, message: "所属时间不能为空", trigger: "blur" }
        ],
        weaveDate: [
          { required: true, message: "编制日期不能为空", trigger: "blur" }
        ],
        beginDate: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
      },
      // 实际开始时间
      beginPickerOptions: {
        disabledDate: (time) => {
          let suatus = true;
          if (suatus && this.form.endDate) {
            suatus = getDateDiff(this.parseTime(time, '{y}-{m}-{d}'), this.form.endDate, 'day') >= 0;
          }
          return !suatus;
        },
      },
      // 实际结束时间
      endPickerOptions: {
        disabledDate: (time) => {
          let suatus = true;
          if (suatus && this.form.beginDate) {
            suatus = getDateDiff(this.parseTime(time, '{y}-{m}-{d}'), this.form.beginDate, 'day') <= 0;
          }
          return !suatus;
        },
      }
    };
  },
  computed: {
    ...mapGetters(["sysProjectId", "sysProjectList"])
  },
  watch: {
    sysProjectId (newVal, oldVal) {
      // 系统顶部选中项目变化
      this.changeProject(newVal);
    },
    filterText (val) {
      this.$refs.tree.filter(val);
    }
  },
  created () {
    this.changeProject();
  },
  methods: {
    changeProject (projectId = this.sysProjectId) {
      this.projectId = projectId;
      this.getBdTree();
    },
    getBdTree () {
      querySupplierTreeList({ projectId: this.projectId }).then((response) => {
        this.treeList = response.data;
        // 选中左侧树
        this.$nextTick(() => {
          if (this.treeList.length > 0) {
            // this.$refs.tree.setCurrentKey(this.treeList[0].id);
            // this.handleNodeClick(this.treeList[0]);
          } else {
            this.treeInfo = {};
            this.queryParams.bdId = null;
            this.queryParams.zdId = null;
            this.materialPlanList = [];
            this.total = 0;
          }
        });
      });
    },
    // 筛选节点
    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick (data) {
      this.treeInfo = data;
      if (data.type == "supplier") {
        this.queryParams.zdId = data.parentId; // 站点ID
        this.queryParams.gysId = data.id; // 供应商ID
        this.handleQuery();
      } else {
        // this.$message.warning('请选择供应商！');
      }
    },

    /** 查询材料计划列表 */
    getList () {
      this.loading = true;
      listMaterialPlan(this.queryParams).then(response => {
        this.materialPlanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        planId: undefined,
        bdId: undefined,
        gysId: this.treeInfo.id,
        type: undefined,
        belongDate: undefined,
        weaveDate: this.parseTime(new Date().getTime(), '{y}-{m}-{d}'),
        beginDate: this.parseTime(getMonthStartAndEnd().start, '{y}-{m}-{d}'),
        endDate: this.parseTime(getMonthStartAndEnd().end, '{y}-{m}-{d}'),
        unit: undefined,
        workflowsStateus: undefined,
        sendStateus: undefined,
        signStateus: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.planId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加材料计划";
    },
    // 更多操作触发
    handleCommand (command, row) {
      switch (command) {
        case "handleUpdate":
          this.handleUpdate(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        case "onExamine":
          this.onExamine(row);
          break;
        default:
          break;
      }
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.loading = true;
      this.reset();
      const planId = row.planId || this.ids;
      getMaterialPlan(planId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改材料计划";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.planId != null) {
            updateMaterialPlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMaterialPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const planIds = row.planId || this.ids;
      this.$modal.confirm('是否确认删除材料计划编号为"' + planIds + '"的数据项？').then(() => {
        this.loading = true;
        return delMaterialPlan(planIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    // 签收
    onSign (row) {
      this.$modal.confirm('是否确认签收材料计划所属期间为"' + this.parseTime(row.belongDate, '{y}年{m}月') + '"的数据项？').then(() => {
        this.loading = true;
        const info = {
          planId: row.planId,
          gysId: row.gysId,
          signStateus: 1,
        };
        return updateMaterialPlan(info);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("签收成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('ma/materialPlan/export', {
        ...this.queryParams
      }, `materialPlan_${new Date().getTime()}.xlsx`);
    },
    // 编辑明细
    onUpdateDeatils (row) {
      this.$refs.planDetailsRef.init(row.planId);
    },
    // 查看报表
    onViewDeatils (row) {
      this.$refs.planDetailsViewRef.init(row.planId);
    },
    // 是否可操作
    canOperation (row) {
      return row.workflowsStateus == '00' || row.workflowsStateus == '33';
    },
    /** 发起审批 */
    onExamine (row) {
      const projectInfo = this.sysProjectList.find(item => item.projectId == this.projectId);
      const info = {
        projectId: this.projectId,
        projectName: projectInfo.projectName,
        bdId: row.bdId,
        zdId: row.zdId,
        gysId: row.gysId,
        planId: row.planId,
      };
      this.$refs.examineAndApproveRef.init(info);
    },
    // 查看流转记录
    showApproveLog (row) {
      const taskForm = {
        procInsId: row.proInsId,// row.procInsId, // 流程实例编号
        taskId: row.taskId,//  row.taskId  // 流程任务编号
      };
      this.$refs.approveLogRef.init(taskForm);
    }
  }
};
</script>
